require 'digest/sha1'
require 'validates_uri_existence_of'

class User < ActiveRecord::Base

  validates_presence_of           :name,:email_addr,:question,:question_answer, :identity_url
  validates_uniqueness_of         :name,:email_addr,:case_sensitive => false
        
  validates_format_of     :email_addr,:with=> /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,:message    => 'email must be valid' 
  validates_uri_existence_of :identity_url, :with =>
        /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix,:message    => 'OpenID URL must be valid' 
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  
  attr_accessible :name, :email_addr, :password, :password_confirmation,:profile, :identity_url,:question,:question_answer
#  attr_protected :hashed_password, :enabled
    
  has_and_belongs_to_many :roles
    has_many :articles 
  
  def validate
    errors.add_to_base("Missing password") if hashed_password.blank?
  end
  
  def self.authenticate(email_addr, password)
    user = self.find_by_email_addr_and_enabled(email_addr,true)#
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end
  
  # 'password' is a virtual attribute
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd

    return if pwd.blank?
        create_new_salt
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  def after_destroy
    if User.count.zero?
      raise "Cant delete last user"
    end
  end
 
   def has_role?(rolename)
    self.roles.find_by_name(rolename) ? true : false
  end
  
  private
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "sdfdsg" + salt # 'sdfdsg' makes it harder to guess
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  

end
